import json
import sys
import pymysql
import requests
import yaml
import pandas as pd
from typing import *


class Function_Help(object):

    def get_yaml_info(self):
        """
        :return:  将yaml文件中的环境信息以字典的形式返回
        """
        # 打开YAML文件
        if sys.platform.lower().startswith('win'):
            with open('D:/wangyu-project/lap_ahyd/Test_lap/base_info.yaml', 'r') as file:
                # 加载YAML数据到字典对象
                data = yaml.safe_load(file)
                return data
        elif sys.platform.lower().startswith('linux'):
            with open('/lap/Test_lap/base_info.yaml', 'r') as file:
                # 加载YAML数据到字典对象
                data = yaml.safe_load(file)
                return data

    def conn_mysql(self, sql: str, connect_info: dict, enforcement=0):
        """
        :param sql:  要执行的sql语句
        :param connect_info: mysql数据库连接信息
        :param enforcement: 是否强制执行，（以select开头的查询语句无需这个传参）
        :return: 将查询结果以列表字典的形式返回[{}, {}]
        """
        connect_info['cursorclass'] = pymysql.cursors.DictCursor
        connect = pymysql.connect(**connect_info)
        cursor = connect.cursor()
        if enforcement == 0:
            try:
                if sql.strip().lower().startswith('select'):
                    cursor.execute(sql)
                    result = cursor.fetchall()
                    return result
                elif sql.strip().lower().startswith('update'):
                    cursor.execute(sql)
                    connect.commit()
                    return 'success'
                elif sql.strip().lower().startswith('insert'):
                    cursor.execute(sql)
                    connect.commit()
                    return 'success'
                else:
                    raise ValueError("目前只支持select update insert")
            except ValueError as e:
                print(f"注意: {e}")
            except Exception as e:
                print(f"发生异常: {e}")
            finally:
                cursor.close()
                connect.close()
        else:
            try:
                cursor.execute(sql)
                result = cursor.fetchall()
                return result
            except Exception as e:
                print(f"发生异常: {e}")
            finally:
                cursor.close()
                connect.close()

    def invoke_interface(self, method: str, url: str, headers: dict, data=None):
        """
        :param method: 接口调用方式，目前只支持get和post
        :param url: 调用的接口url
        :param headers: 消息头
        :param data: 接口传参
        :return: 接口响应-json格式
        """
        if method == 'get':
            response = requests.get(url=url, headers=headers)
            result = json.loads(response.text)
            return result
        elif method == 'post':
            response = requests.post(url=url, headers=headers, data=json.dumps(data))
            result = json.loads(response.text)
            return result

    def data_compare(self, data_api: List[Dict], data_sql: List[Dict], api_sorted_value: str, sql_sorted_value: str):
        """
        :param data_api: 接口返回的数据
        :param data_sql: sql返回的数据
        :param api_sorted_value: 接口返回数据的排序字段
        :param sql_sorted_value: sql返回数据的排序字段
        :return: 比对结果 True 或者 False
        """
        pd_api = pd.DataFrame(data_api)
        pd_sql = pd.DataFrame(data_sql)
        api_sorted = pd_api.sort_values(api_sorted_value).reset_index(drop=True)
        sql_sorted = pd_sql.sort_values(sql_sorted_value).reset_index(drop=True)
        return api_sorted.equals(sql_sorted)

    def cron_transform_description(self, task_type: str, cron: str):
        """
        :param task_type:  任务类型
        :param cron:  cron表达式
        :return: 根据不同的任务类型输出不同的cron表达式含义
        """
        week_dict = {
            '1': '星期一',
            '2': '星期二',
            '3': '星期三',
            '4': '星期四',
            '5': '星期五',
            '6': '星期六',
            '7': '星期天'
        }
        if task_type == 'once':
            result = 'cron表达式为空'
        elif task_type == 'day':
            corn_list = cron.split(' ')
            hour = corn_list[2]
            minute = corn_list[1]
            if minute == '0':
                result = f'每天{hour}时执行一次'
            else:
                result = f'每天{hour}时{minute}分执行一次'
        elif task_type == 'week':
            corn_list = cron.split(' ')
            week = week_dict[corn_list[5]]
            hour = corn_list[2]
            minute = corn_list[1]
            if minute == '0':
                result = f'每周的{week}{hour}时执行一次'
            else:
                result = f'每周的{week}{hour}时{minute}分执行一次'
        elif task_type == 'month':
            corn_list = cron.split(' ')
            day = corn_list[3]
            hour = corn_list[2]
            minute = corn_list[1]
            if minute == '0':
                result = f'每月第{day}天{hour}时执行一次'
            else:
                result = f'每月第{day}天{hour}时{minute}分执行一次'
        else:
            result = '暂不支持该任务类型'
        return result


if __name__ == '__main__':
    test = Function_Help()
    result = test.get_yaml_info()
    print(result)
